﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Configuration;
using DotNetMigrations.Commands;
using System.Diagnostics;
using System.Reflection;

namespace DotNetMigrations
{
	public class Program
	{
		public static string MigrationDir { get; set; }

		static int Main(string[] args)
		{
			//	set the directory path that migration scripts are stored in
            if (!string.IsNullOrEmpty(AppSettings.MigrateFolder))
            {
                MigrationDir = AppSettings.MigrateFolder;
            }
            else
            {
                MigrationDir = Path.Combine(Directory.GetCurrentDirectory(), "migrate");
            }

			//	make sure we have at least 1 argument
			if (args.GetLength(0) == 0)
				goto SHOW_HELP;

			//	get a new array of arguments to pass to the command
			//	by removing the first item (the command name)
			//	from the application's arguments
			string[] cmdArgs = new string[args.GetLength(0) - 1];
			Array.ConstrainedCopy(args, 1, cmdArgs, 0, args.GetLength(0) - 1);

			//	get an instance of the command to run
			ConsoleCommand cmd = ConsoleCommandFactory.GetCommand(args[0], cmdArgs);
			if (cmd == null)
			{
				//	command name doesn't exist...
				goto SHOW_HELP;
			}
			if (cmd.ValidateArgs() == false)
			{
				//	arguments were invalid for the command...
				goto SHOW_HELP;
			}

			bool success = cmd.Run();
			if (success)
				return 0;	//	success code
			else
				return -1;	//	error code

		//	if we get here, they didn't
		//	enter the command right, lets help them out
		SHOW_HELP:
			Output.HelpContent();
			return -2;	//	help code
		}

		/// <summary>
		/// Get the application version from AssemblyInfo.
		/// </summary>
		public static string GetAppVersion()
		{
			FileVersionInfo v = FileVersionInfo.GetVersionInfo(
				Assembly.GetExecutingAssembly().Location);
			return v.ProductMajorPart + "." + v.ProductMinorPart;
		}
	}
}
